package cn.jdemo.juc.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * volatile数据以主内存为基准，不管是更新还是获取
 *
 * @description
 * @date 2020/12/4
 */
public class DemoVolatile01 {

    private static volatile Integer num01 = 0;
    private static Integer num02 = 0;

    public static void main(String[] args) {
        test01();
    }
    public static void test01(){
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName() + "_volatile_1:" + num01);//Thread-0_volatile_1:0
                while (num01 == 0){
                    // volatile修饰的类型可以从主内存获取
                }
            } finally {
                System.out.println(Thread.currentThread().getName() + "_volatile_2:" + num01);//Thread-0_volatile_2:1
            }
        }).start();

        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName() + "_no_volatile_1:" + num02);//Thread-1_no_volatile_1:0
                while (num02 == 0){
                    // 从当前线程的工作内存获取，所以一直是0
                }
            } finally {
                System.out.println(Thread.currentThread().getName() + "_no_volatile_2:" + num02);//被while(num02==0)拦住
            }
        }).start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2L);
                num01++;// 更新后，刷新到主内存
                num02++;// 更新后，刷新到主内存
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // condition.signal();
            }
        }).start();
    }
}
